#!/usr/bin/env python
# -*- coding: UTF-8 -*-
# @Project:     py_utils
# @File:        u_time.py
# @Author:      Fan GuiChuan
# @Date:        2024/8/8 16:04
# @Version:     Python3.7
# @Description:
import datetime
import time


class TimeTool(object):
    @staticmethod
    def get_time_length(time_str: str):
        """
        获取时间长度，如1年前、1个月前、1天前、1小时前、1分钟前、1秒前
        :param time_str: "%Y-%m-%d %H:%M:%S"
        """
        dt = datetime.datetime.strptime(time_str, "%Y-%m-%d %H:%M:%S").timestamp()
        cur_timestamp = time.time()
        t_len = cur_timestamp - dt

        dt = datetime.datetime.fromtimestamp(t_len)
        year = dt.year - 1970
        if year:
            return f'{year}年前'
        month = dt.month - 1
        if month:
            return f'{month}个月前'
        day = dt.day - 1
        if day:
            return f'{day}天前'
        hour = int(t_len / (60 * 60))
        if hour:
            return f'{hour}小时前'
        minute = int(t_len / 60)
        if minute:
            return f'{minute}分钟前'

        return f'{int(t_len)}秒前'


if __name__ == '__main__':
    dt = TimeTool.get_time_length("2024-08-08 16:09:33")
    print(f"dt: {dt}")
